package buildrobot_info

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/api/service/build"
	"go_server/game_server/api/service/currency"
	"go_server/game_server/api/service/item"
	"go_server/game_server/constants"
	"go_server/game_server/event_manager"
	"go_server/game_server/event_manager/event_data/event_impl"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"time"
)

func (s *Buildrobot_info_service) GM_BuildRobotUpgradeByItem(conn ziface.IConnection, roleid int64, params []string) pb.ErrorCodeManager {

	msg := &pb.BuildRobotUpgradeByItemC2S{
		Items: make(map[int32]int32, 10),
	}

	robot := s.LoadByRoleId(roleid)
	if robot != nil && robot.BuildData != nil {
		for _, bv := range robot.BuildData {
			msg.Buildmapid = bv.Build_info_mapId       //建筑地图id
			msg.Buildcfgid = bv.Build_info_cfgBuildId  //建筑配置id
			msg.Buildserid = bv.Build_info_svrConfigId //建筑服务器id
			break
		}
	}

	if vals, ok := item.GetItemDataByBagShow(constants.Item_Bagshow_Accelerate, -1); ok {
		for id, _ := range vals {
			msg.Items[id] = 1
		}
	}
	bag.AddItemBatch(roleid, msg.Items)

	return s.S2C_BuildRobotUpgradeByItem(conn, roleid, msg)
}

func (s *Buildrobot_info_service) S2C_BuildRobotUpgradeByItem(conn ziface.IConnection, roleid int64, msg *pb.BuildRobotUpgradeByItemC2S) pb.ErrorCodeManager {
	if len(msg.Items) > 0 {
		itemdatas := make(map[int32]*item.Cache_Item_Config_Data)       //使用的物品
		currencydatas := make(map[int32]*currency.Currency_RelatedData) //使用的货币

		c2sCurrencys := make(map[int32]int32)
		c2sItems := make(map[int32]int32)
		for id, count := range msg.Items {
			if c, c1 := currency.GetCurrency(id); c1 { //是否是货币减少时间
				if c.TransAccelerateMillisecond > 0 { //时间加速，使用的货币
					currencydatas[id] = c
					c2sCurrencys[id] = count
				}
			}

			if d, d1 := item.GetItemData(id); d1 { //是否是道具加速
				if d.IsAccelerateBuild() { //建造加速
					itemdatas[id] = d
					c2sItems[id] = count
				}
			}
		}

		robot := s.LoadByRoleId(roleid)
		if robot != nil {
			build_info_id := build.CombinBuildKey(roleid, msg.Buildmapid, msg.Buildcfgid, msg.Buildserid)
			upBuild := &Cache_buildrobot_info_build_data{}
			if bv, ok := robot.BuildData[build_info_id]; ok { //如果是已经有过升级操作
				upBuild = bv
				if len(c2sCurrencys) > 0 { //使用货币建造
					upBuild.RobotSerids = robot.GetRobotSerids()                                 //不论建造状态，时间一律按全机器人算
					upBuild.CalculateUpgradeTime(robot.TransVolume, robot.GetRobotBySerid, true) //按全机器人计算时间
				}
			} else { //没有过升级操作,加入到升级队列
				upBuild.SetBuild_info_id(build_info_id)
				upBuild.BeforeLv, upBuild.AfterLv = build.NextBuildLevel(build_info_id)

				upBuild.RobotSerids = robot.GetRobotSerids()                                 //不论建造状态，时间一律按全机器人算
				upBuild.CalculateUpgradeTime(robot.TransVolume, robot.GetRobotBySerid, true) //按全机器人计算时间
				robot.BuildData[build_info_id] = upBuild
			}

			if !build.TestBuildCanLevelUp(upBuild.Build_info_id) {
				return pb.ErrorCodeManager_BUILDROBOTINFO_NOT_RESENOUGH
			}
			zlog.Debugf("S2C_BuildRobotUpgradeByItem=>RoleId:%v BuildId:%v UpgradeTime:%v(秒) c2sMsg:%v", roleid, upBuild.Build_info_id, upBuild.UpgradeTime, msg)
			surplusMillitime := upBuild.UpgradeTime * 1000 //当前建筑剩余的建造时间
			//使用物品加速
			useitems := make(map[int32]int32)
			if len(c2sItems) > 0 { //使用物品建造
				for id, count := range c2sItems {
					for i := 0; i < int(count); i++ {
						if _, ok := useitems[id]; ok {
							useitems[id] = 0
						}
						surplusMillitime -= itemdatas[id].Accelerate_Millisecond
						useitems[id]++
						if surplusMillitime <= 0 {
							break
						}
					}
					if surplusMillitime <= 0 {
						break
					}
				}
			}

			//使用货币加速
			usecurrencys := make(map[int32]int32)
			if surplusMillitime > 0 {
				if len(c2sCurrencys) > 0 { //使用货币建造
					for id, count := range c2sCurrencys {
						for i := 0; i < int(count); i++ {
							if _, ok := c2sCurrencys[id]; ok {
								c2sCurrencys[id] = 0
							}
							surplusMillitime -= currencydatas[id].TransAccelerateMillisecond
							usecurrencys[id]++
							if surplusMillitime <= 0 {
								break
							}
						}
						if surplusMillitime <= 0 {
							break
						}
					}
				}
			}

			if surplusMillitime <= 0 { //如果结束时间<开始时间
				upBuild.StartMilliTime = upBuild.EndMilliTime
				upBuild.EndMilliTime = time.Now().UnixMilli()
			} else {
				upBuild.StartMilliTime = time.Now().UnixMilli()
				upBuild.EndMilliTime = upBuild.StartMilliTime + surplusMillitime
			}
			upBuild.UpgradeTime = surplusMillitime

			lvupTime := build.GetBuildLvupTime(upBuild.Build_info_id)
			if lvupTime <= 0 {
				return pb.ErrorCodeManager_HERO_INFO_ERROR_BUILDROBOTUPGRADEBYITEM
			}

			speedUpTime := lvupTime - upBuild.EndMilliTime

			build.SetBuildLvupTime(upBuild.Build_info_id, upBuild.EndMilliTime)
			if upBuild.UpgradeTime <= 0 {
				totalCost := util.MergeMaps(useitems, usecurrencys)
				bag.SubItemBatch(roleid, totalCost)
				Buildrobot_info_serviceObj.S2C_BuildRobotUpgradeSuc(conn, robot)
				event_manager.EventManagerObj.FireEventData(event_impl.NewBuildSpeedUpEvent(conn, speedUpTime))
			} else {
				return pb.ErrorCodeManager_HERO_INFO_ERROR_BUILDROBOTUPGRADEBYITEM
			}
		} else {
			return pb.ErrorCodeManager_BUILDROBOTINFO_NOT_ROLE
		}
	}


	return pb.ErrorCodeManager_SUCCESS
}
